#!/bin/bash
# 服务器一键部署脚本（CentOS 7.x）
# 功能：安装系统基础依赖 + MySQL 8.0
# 执行：sudo ./setup_MySQL8_server.sh

# -------------------------- 基础函数定义 --------------------------
# 1. 错误提示并退出
error_exit() {
    echo -e "\n❌ 错误：$1"
    exit 1
}

# 2. 进度提示
progress_msg() {
    echo -e "\n=== $1 ==="
}

# 3. 密码复杂度校验（返回0=符合，1=不符合）
check_password() {
    local pwd="$1"
    # 条件：8位以上 + 含大小写 + 含数字 + 含特殊字符（!@#$%^&*()）
    if [ ${#pwd} -lt 8 ]; then
        return 1
    elif ! echo "$pwd" | grep -qE '[A-Z]'; then
        return 1
    elif ! echo "$pwd" | grep -qE '[a-z]'; then
        return 1
    elif ! echo "$pwd" | grep -qE '[0-9]'; then
        return 1
    elif ! echo "$pwd" | grep -qE '[!@#$%^&*()?]'; then
        return 1
    else
        return 0
    fi
}

# 4. 交互输入MySQL信息（避免硬编码）
input_mysql_info() {
    progress_msg "请输入MySQL配置信息（将用于创建数据库和用户）"
    
    # 输入root密码（并校验）
    while true; do
        read -p "1. 输入MySQL root密码（要求：8位+大小写+数字+特殊字符）：" -s ROOT_PWD
        echo
        if check_password "$ROOT_PWD"; then
            break
        else
            echo "⚠️  密码不符合要求！请重新输入（例：Root@123）"
        fi
    done

    # 输入项目数据库名（默认order_db）
    read -p "2. 输入项目数据库名（默认：order_db）：" DB_NAME
    DB_NAME=${DB_NAME:-order_db}

    # 输入项目用户名（默认order_user）
    read -p "3. 输入项目数据库用户名（默认：order_user）：" DB_USER
    DB_USER=${DB_USER:-order_user}

    # 输入项目用户密码（并校验）
    while true; do
        read -p "4. 输入项目用户密码（要求同root密码）：" -s USER_PWD
        echo
        if check_password "$USER_PWD"; then
            break
        else
            echo "⚠️  密码不符合要求！请重新输入（例：User@456）"
        fi
    done

    # 确认信息
    echo -e "\n=== 确认MySQL配置 ==="
    echo "root密码：****（您输入的）"
    echo "项目数据库名：$DB_NAME"
    echo "项目用户名：$DB_USER"
    echo "项目用户密码：****（您输入的）"
    read -p "是否继续？（y/n）：" confirm
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        error_exit "用户取消部署"
    fi
}

# -------------------------- 部署流程 --------------------------
# 校验root权限
if [ "$(id -u)" -ne 0 ]; then
    error_exit "请用root权限执行：sudo ./server_onekey_deploy.sh"
fi

echo -e "\n============================================="
echo "服务器一键部署脚本（CentOS 7.x）"
echo "功能：安装基础依赖+MySQL8.0"
echo "============================================="
read -p "按回车键开始部署..."

# 交互输入MySQL信息（敏感信息不硬编码）
input_mysql_info


# 安装基础依赖
progress_msg "安装系统基础依赖"
yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make libffi-devel perl-Test-Simple >/dev/null 2>&1 || error_exit "基础依赖安装失败"
echo "✅ 系统初始化完成"


# -------------------------- 安装MySQL 8.0 --------------------------
progress_msg "安装MySQL 8.0并配置"
cd || error_exit "切换到根目录失败"

# 下载并安装仓库
wget -q https://dev.mysql.com/get/mysql84-community-release-el7-1.noarch.rpm || error_exit "MySQL仓库包下载失败"
yum install -y mysql84-community-release-el7-1.noarch.rpm >/dev/null 2>&1 || error_exit "MySQL仓库安装失败"

# 安装MySQL服务
yum install -y mysql-community-server --nogpgcheck >/dev/null 2>&1 || error_exit "MySQL服务安装失败"

# 启动服务
systemctl start mysqld || error_exit "MySQL服务启动失败"
if ! systemctl is-active --quiet mysqld; then
    error_exit "MySQL服务启动后未正常运行"
fi
echo "✅ MySQL服务已启动"

# 获取临时密码
TEMP_PWD=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')
if [ -z "$TEMP_PWD" ]; then
    error_exit "无法获取MySQL临时密码"
fi

# 重置root密码
mysql -uroot -p"$TEMP_PWD" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$ROOT_PWD';" >/dev/null 2>&1 || error_exit "root密码重置失败（请确认密码复杂度）"
echo "✅ MySQL root密码重置完成"

# 创建数据库和用户
mysql -uroot -p"$ROOT_PWD" -e "
CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` DEFAULT CHARSET utf8;
CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$USER_PWD';
CREATE USER IF NOT EXISTS '$DB_USER'@'%' IDENTIFIED BY '$USER_PWD';
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'localhost' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
" >/dev/null 2>&1 || error_exit "MySQL数据库/用户创建失败"
echo "✅ MySQL数据库和用户配置完成"

# -------------------------- 部署完成 --------------------------
echo -e "\n============================================="
echo "🎉 服务器一键部署MySQL 8.0完成！"
echo "4. MySQL：8.0（服务已启动）"
echo -e "\n【MySQL关键信息】（请妥善保存）"
echo "1. root账号：root / $ROOT_PWD"
echo "2. 项目数据库：$DB_NAME"
echo "3. 项目账号：$DB_USER / $USER_PWD"
echo -e "\n【后续操作建议】"
echo "1. 清除命令行历史：history -c"
echo "2. 测试MySQL登录：mysql -uroot -p"
echo "3. 远程连接：用Navicat等工具，IP填服务器地址，账号用 $DB_USER"
echo "============================================="